package com.mischa.doedeljas.server;

import java.io.IOException;
import java.net.Socket;
import java.util.Vector;

import com.mischa.network.Server;

public class DoedeljasServer 
	extends Server
{
	private Vector<Player> clients = new Vector<Player>();
	private Vector<Game> games = new Vector<Game>();
	
	public static void main(String[] args) {
		
		
		int port = args.length > 0 ? Integer.parseInt(args[0]) : 1234;
		try {
			new DoedeljasServer(port).start();
			
			System.out.println("Doedeljas server running on port " + port);
		} catch (IOException e) {
			System.out.println("Doedeljas server failed to start: " + e.getMessage());
			e.printStackTrace();
		}
	}
	
	public DoedeljasServer(int port) {
		super(port);
	}

	@Override
	public void clientConnected(Socket socket) 
	{
		Player newPlayer = new Player(socket, this);
		newPlayer.start();
		clients.add(newPlayer);		
	}
	
	public void join(int gameId, Player player)
	{
		for (Game game : games)
		{
			if (game.getGameId() == gameId)
			{
				if (game.addPlayer(player))
				{
					System.out.println("Client joined game " + gameId);
				}
				else
				{
					join(gameId + 1, player);
				}
				return;
			}		
		}
		
		Game newGame = new Game(gameId);
		newGame.addPlayer(player);
		games.add(newGame);
		System.out.println("Game " + gameId + " created and client joined.");
	}
}
